/**
 * 3. 无重复字符的最长子串
 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 */

/**
 * @param {string} s
 * @return {number}
 */
const lengthOfLongestSubstring = (s) => {
  const sLength = s.length;
  if (!sLength) return 0;
  const previous = [];
  previous[s.charCodeAt(0)] = 0;
  let currentLength = 1;
  let maxLength = 1;
  let preRepeat = 0;
  for (let i = 1; i < sLength; i += 1) {
    const charCode = s.charCodeAt(i);
    const repeatIndex = previous[charCode];
    if (repeatIndex >= 0) {
      for (let j = preRepeat; j <= repeatIndex; j += 1) {
        previous[s.charCodeAt(j)] = -1;
      }
      preRepeat = repeatIndex + 1;
      currentLength = i - repeatIndex;
    } else {
      currentLength += 1;
    }
    if (currentLength > maxLength) {
      maxLength = currentLength;
    }
    previous[s.charCodeAt(i)] = i;
  }
  return maxLength;
};

console.log(lengthOfLongestSubstring('') === 0);
console.log(lengthOfLongestSubstring('a') === 1);
console.log(lengthOfLongestSubstring('ab') === 2);
console.log(lengthOfLongestSubstring('abc') === 3);
console.log(lengthOfLongestSubstring('bbbbb') === 1);
console.log(lengthOfLongestSubstring('abcabcbb') === 3);
console.log(lengthOfLongestSubstring('pwwkew') === 3);
console.log(lengthOfLongestSubstring('abb') === 2);
console.log(lengthOfLongestSubstring('dvdf') === 3);
